package com.example.shgt;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MyPostsActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private MyPostsAdapter adapter;
    private List<Post> postList;
    private long userId; // 声明 userId 变量

    // 数据模型类
    public static class Post {
        private String username;
        private double price;
        private String content;
        private String avatar;
        private long createTime; // 添加创建时间字段

        // Getters
        public String getUsername() { return username; }
        public double getPrice() { return price; }
        public String getContent() { return content; }
        public String getAvatar() { return avatar; }
        public long getCreateTime() { return createTime; } // 添加 getter
    }

    // 响应模型类
    public static class MyPostsResponse {
        private int code;
        private Data data;

        public static class Data {
            private List<Post> records;

            public List<Post> getRecords() { return records; }
        }

        public int getCode() { return code; }
        public Data getData() { return data; }
    }

    // 适配器类
    private class MyPostsAdapter extends RecyclerView.Adapter<MyPostsAdapter.ViewHolder> {
        private List<Post> posts;

        public MyPostsAdapter(List<Post> posts) {
            this.posts = posts;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public TextView usernameTextView, priceTextView, contentTextView, createTimeTextView; // 添加 createTimeTextView
            public ImageView avatarImageView;

            public ViewHolder(View view) {
                super(view);
                usernameTextView = view.findViewById(R.id.tv_username);
                priceTextView = view.findViewById(R.id.tv_price);
                contentTextView = view.findViewById(R.id.tv_content);
                createTimeTextView = view.findViewById(R.id.tv_create_time); // 初始化 createTimeTextView
                avatarImageView = view.findViewById(R.id.iv_avatar);
            }
        }


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.item_post, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Post post = posts.get(position);
            holder.usernameTextView.setText(post.getUsername());
            holder.priceTextView.setText("¥" + post.getPrice());
            holder.contentTextView.setText(post.getContent());

            // 格式化创建时间并显示
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String formattedDate = sdf.format(new Date(post.getCreateTime())); // 使用 getCreateTime
            holder.createTimeTextView.setText(formattedDate);

            // 加载头像
            Glide.with(holder.itemView.getContext()).load(post.getAvatar()).into(holder.avatarImageView);
        }


        @Override
        public int getItemCount() {
            return posts.size();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_posts);

        recyclerView = findViewById(R.id.rv_my_posts);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        postList = new ArrayList<>();
        adapter = new MyPostsAdapter(postList);
        recyclerView.setAdapter(adapter);

        ImageView backButton = findViewById(R.id.iv_back);
        backButton.setOnClickListener(v -> finish());

        // 从 SharedPreferences 获取用户ID
        SharedPreferences sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE);
        userId = Long.parseLong(sharedPreferences.getString("userId", "0")); // 获取并解析用户ID

        fetchMyPosts(userId);
    }


    private void fetchMyPosts(long userId) {
        String url = "https://api-store.openguet.cn/api/member/tran/goods/myself?userId=" + userId;

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .addHeader("appId", "479dbe79299a4653ada0432942111871")
                .addHeader("appSecret", "14687c6d2cc860b264339b1d93bf409f2bb6c")
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Content-Type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("API Failure", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseData = response.body().string();
                    parseResponseData(responseData);
                } else {
                    Log.e("API Error", "Response code: " + response.code());
                }
            }
        });
    }


    private void parseResponseData(String jsonData) {
        MyPostsResponse response = new Gson().fromJson(jsonData, MyPostsResponse.class);
        if (response.getCode() == 200 && response.getData() != null) {
            List<Post> records = response.getData().getRecords();
            runOnUiThread(() -> {
                postList.clear();
                postList.addAll(records);
                adapter.notifyDataSetChanged();
            });
        } else {
            Log.e("API Error", "Invalid response code or data is null");
        }
    }
}
